package com.Sdebruijn.curriculumvitae.swipey;

import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.SparseArray;

public class SwipeyPagerAdapter extends FragmentPagerAdapter {

	private final Context context;
	private final FragmentManager fm;
	private final ArrayList<TabInfo> tabs = new ArrayList<TabInfo>();
	private final SparseArray<Fragment> fragmentMap = new SparseArray<Fragment>();

	static final class TabInfo {
		private final Class<?> clss;
		private final Bundle args;

		TabInfo(Class<?> _class, Bundle _args) {
			clss = _class;
			args = _args;
		}
	}

	public SwipeyPagerAdapter(final FragmentManager fm, final Context context) {
		super(fm);
		this.fm = fm;
		this.context = context;
	}

	public void addTab(Class<?> clss, Bundle args) {
		TabInfo info = new TabInfo(clss, args);
		tabs.add(info);
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return tabs.size();
	}

	@Override
	public Fragment getItem(final int position) {

		TabInfo info = tabs.get(position);

		Fragment fragment = fm.findFragmentByTag(info.clss.getName());
		if (fragment == null) {
			fragment = Fragment.instantiate(context, info.clss.getName(),
					info.args);
		}

		fragmentMap.put(position, fragment);

		return fragment;
	}

	public Fragment getFragment(final int position) {
		Fragment fragment = fragmentMap.get(position);

		if (fragment == null) {
			fragment = getItem(position);
		}

		return fragment;
	}
}